<template>
    <!-- 详情页 -->
    <div class="detail">
        <!-- 导入头部 -->
        <div class="Header">
            <theHeader></theHeader>
        </div>
        <!-- 内容 -->
        <div class="content">
            <!-- 上部分 -->
            <div class="top">
                <!-- 图片容器 -->
                <div class="detailimg">
                    <el-card class="box-card" style=" width: 360px;">
                        <div class="text item">
                            <el-image style="width: 300px;height: 300px;"
                                :src="postimgurl"  :lazy="true" fit="fit"></el-image>
                        </div>
                    </el-card>
                </div>
                <!-- 帖子信息 -->
                <div class="detaiinfo" style="margin-left: 36px;">
                    <el-card class="box-card" style="width: 600px;">
                        <div class="text item">
                            <!-- 标题与图标 -->
                            <div class="title" style="display: flex;align-items: center;position: relative;">
                                <h3>{{ post.title }}</h3>
                                <!-- 未点赞时的状态 -->
                                <!-- 未点赞时显示 -->
                                <img src="../assets/img/点赞.png"
                                    style="height: 22px;cursor: pointer;position: absolute;right: 26px;" @click="like()"
                                    v-show="!isLike">

                                <!-- 点赞时显示 -->
                                <img src="../assets/img/点赞-激活.png"
                                    style="height: 22px;cursor: pointer;position: absolute;right: 26px;"
                                    @click="Nolike()" v-show="isLike">

                                <span
                                    style="color: #F56C6C;position: absolute;right: 0;font-size: 16px;font-family: Arial, Helvetica, sans-serif;margin-top: 4px;">{{
                                        post.numberLikes
                                    }}</span>
                            </div>
                            <!-- 内容 -->
                            <p style="font-family: '微软雅黑';">
                                {{ post.content }}
                            </p>
                            <!-- 帖子发布时间等 -->
                            <div class="publishinformation" style="display: flex;flex-direction: column;">
                                <span>发布时间：{{ post.postDate }}</span>
                                <span>帖子分类：{{ displayContent }}</span>
                                <span @click="touser()" style="cursor: pointer;">作者：{{ post.authorName }}</span>
                            </div>

                        </div>

                        <el-button type="primary" icon="el-icon-edit" circle style="float: right;margin-bottom: 12px;"
                            size="small" @click="edit" v-show="isedit"></el-button>
                    </el-card>
                </div>
            </div>
            <!-- 评论 -->
            <el-card class="box-card" style="padding: 10px;margin-top: 18px;">
                <div class="comment">
                    <!-- 用户头像 -->
                    <el-image style="width: 40px; height: 40px; border-radius:32px"
                        :src="require('../assets/img/head_sculpture.jpg')"></el-image>
                    <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="commenttext" resize="none"
                        autofocus="true" style="width: 980px;margin-left: 12px;">
                    </el-input>
                </div>
                <el-button type="primary" style="float: right;margin-top: 12px;margin-right: 12px;"
                    @click="comment()">发表评论</el-button>
            </el-card>

            <!-- 评论区 -->
            <div class="commentlist" v-show="pageShow">
                <el-card class="box-card">
                    <!-- 用户头像等 -->
                    <div class="comment_user" v-for="item in commentlist">
                        <div class="user_img"
                            style="display: flex;align-items: center;width: 166px;white-space: nowrap;overflow: hidden; text-overflow: ellipsis;">
                            <el-image style="width: 40px; height: 40px; border-radius:32px;margin-left: 12px;"
                                :src="require('../assets/img/head_sculpture.jpg')"></el-image>
                            <span style="color: #303133;font-family: '微软雅黑';margin-left: 12px;">
                                {{ item.userCommentDto.username }}</span>
                        </div>
                        <!-- 评论内容等 -->
                        <div class="comment_content" style="margin-left: 146px;display: flex;flex-direction: column;">
                            <div style="margin-top: 20px;font-family:'Hiragino Sans GB';">{{ item.commentContent }}
                            </div>
                            <span style="margin-top: 20px;color: #909399;">{{ item.commentTime }}</span>
                        </div>
                    </div>
                </el-card>

            </div>
        </div>
        <!-- 弹窗   -->
        <el-dialog title="" :visible.sync="dialogFormVisible" width="30%" :close-on-click-modal="false">
            <el-form :model="post">
                <el-form-item label="帖子名称" label-width="150px">
                    <el-input v-model="post.title" autocomplete="off" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="帖子内容" label-width="150px">
                    <el-input type="textarea" v-model="post.content" autocomplete="off" style="width: 80%"></el-input>
                </el-form-item>
                <el-form-item label="图片" label-width="150px">
                    <el-upload action="http://localhost:9001/api/file/upload" multiple :on-success="handleSuccess"
                        ref="upload">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save()">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 分页 -->
        <div class="page" style="margin: 24px auto;display: flex;justify-content: center;" v-show="pageShow">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page.sync="currentPage" :page-size="pageSize" :page-sizes="[3, 6, 9, 12]"
                layout="total, prev, pager, next" :total="total">
            </el-pagination>
        </div>
        <el-empty :image-size="200" description="暂无评论" v-show="!pageShow"></el-empty>
        <!-- 导入尾部 -->
        <div class="Footer">
            <theFooter></theFooter>
        </div>

    </div>



</template>


<script>
// 导入头部,用户资料侧边栏以及底部
import theHeader from '@/components/header.vue';
import theFooter from '@/components/footer.vue';
//导入api
import API from "@/api/request";


export default {
    name: 'detail',
    inject: ['reload'],
    components: {
        theHeader,
        theFooter
    },
    data() {
        return {
            //接收传递过来的帖子id
            postId: '',
            //接收传递过来的类型
            type: '',
            //接受传递过来的作者id
            stuId: '',
            commenttext: '',
            commentlist: [],
            //数据总数
            total: 0,
            //当前页
            currentPage: 1,
            //每页数量
            pageSize: 3,
            //控制分页显示
            pageShow: false,
            //存放帖子的对象
            post: {},
            //判断是否点赞 默认为false
            isLike: false,
            //用户
            user: {},
            imgurl: '',
            dialogFormVisible: false,
            isedit:false,
            postimgurl:''
        }

    },
    methods: {
        //获取评论
        getComment() {
            API.get("/api/Comment/pageList", {
                params: {
                    postId: this.postId,
                    commentType: this.type,
                    pageNum: this.currentPage,
                    pageSize: this.pageSize
                }
            }).then(res => {
                if (res.data.code === 200) {
                    console.log(res.data.data)
                    this.total = res.data.data.total;
                    this.currentPage = res.data.data.current;
                    this.commentlist = res.data.data.comments;
                    console.log(this.commentlist);
                    //当评论数量为0时,不显示分页列表,显示空白页
                    if (this.total > 0) {
                        this.pageShow = true;
                    }
                }

            })
        },
        //获取帖子
        getPost() {
            API.get("/api/plateManagement/findByIdAndType", {
                params: {
                    postId: this.postId,
                    commentType: this.type,
                }
            }).then(res => {
                if (res.data.code === 200) {
                    this.post = res.data.data;
                    console.log("对象")
                    console.log(this.post);
                    this.postimgurl=this.post.postImg;
                }

            })
        },
        //判断当前用户是否点赞
        getUserIsLike() {
            API.get("/api/plateManagement/isLike", {
                params: {
                    studentId: this.user.studentId,
                    postId: this.postId,
                    postType: this.type
                }
            }).then(res => {
                if (res.data.code === 200) {
                    console.log("点赞")
                    console.log(res.data)
                    if (res.data.data == true) {
                        this.isLike = true;
                    }
                }

            })
        },
        //控制页数的函数
        handleSizeChange(val) {
            this.pageSize = val;
            console.log(`每页 ${val} 条`);
            this.getComment();

        },
        // 控制页码的函数
        handleCurrentChange(val) {
            this.currentPage = val;
            console.log("查看当前页" + this.currentPage);
            console.log(`当前 ${val} 页`);
            this.getComment();
        },
        like() {
            console.log("用户id", this.user.studentId);
            API.post("/api/plateManagement/userlikes", {
                userId: this.user.studentId,
                postId: this.postId,
                postType: this.type
            }).then(res => {
                console.log(res)
                if (res.data.code == 200) {
                    this.$message({
                        message: '点赞成功!',
                        type: 'success'
                    });

                    // 延迟刷新页面，确保消息提示能够显示
                    setTimeout(() => {
                        this.reload();
                    }, 1000); // 1秒后刷新页面
                }
            }).catch(error => {
                console.log(error);
                this.$message({
                    message: '点赞失败!',
                    type: 'error'
                });
            });
        },

        //取消点赞
        Nolike() {
            console.log("用户id", this.user.studentId)
            API.post("/api/plateManagement/userNolikes", {
                userId: this.user.studentId,
                postId: this.postId,
                postType: this.type
            }).then(res => {
                console.log("取消")
                console.log(res)
                if (res.data.code == 200) {
                    console.log("取消" + res)
                    this.$message({
                        message: '取消点赞成功!',
                        type: 'success'
                    });

                    // 延迟刷新页面，确保消息提示能够显示
                    setTimeout(() => {
                        this.reload();
                    }, 1000); // 1秒后刷新页面
                }
            }).catch(error => {
                console.log(error)
                this.$message({
                    message: '取消失败!',
                    type: 'warning'
                });
            })
            this.reload()
        },
        //评论
        comment() {
            if (!this.commenttext) {
                this.$message({
                    message: '请输入评论内容!',
                    type: 'warning'
                });
            }
            API.post("/api/plateManagement/comment", {
                studentId: this.user.studentId,
                postId: this.postId,
                commentType: this.type,
                commentContent: this.commenttext,
                name: this.user.username
            }).then(res => {
                console.log("取消")
                console.log(res)
                if (res.data.code == 200) {
                    this.$message({
                        message: '评论成功！',
                        type: 'success'
                    });
                }

            }).catch(error => {
                console.log(error)
                this.$message({
                    message: '评论失败！',
                    type: 'warning'
                });

            })
            // 延迟刷新页面，确保消息提示能够显示
            setTimeout(() => {
                this.reload();
            }, 1000); // 1秒后刷新页面
        },
        edit() {
            console.log("修改")
            this.dialogFormVisible = true;
        },
        handleSuccess(res) {
            console.log(res)
            //修改图片路径
            this.imgurl = res.data;
            console.log("图片" + this.imgurl)
        },
        save() {
            if (this.post.postType == 1) {
                console.log(this.post)
                API.put("/api/lifeSharing/update", {
                    "id": this.post.postId,
                    "name": this.post.title,
                    "content": this.post.content,
                    "type":this.post.postType,
                    "postImage":this.imgurl
                }).then(res => {
                    if (res.data.code === 200) {
                        this.$message.success("操作成功!");
                        this.dialogFormVisible = false;
                        this.reload()
                    } else {
                        console.error("API 请求失败", res);
                    }
                }).catch(error => {
                    console.error("API 请求错误", error);
                });
            } else {
                console.log(this.post)
                API.put("/api/learningExchange/update", {
                    "id": this.post.postId,
                    "name": this.post.title,
                    "content": this.post.content,
                    "type":this.post.postType,
                    "postImage":this.imgurl
                }).then(res => {
                    if (res.data.code === 200) {
                        this.$message.success("操作成功!");
                        this.dialogFormVisible = false;
                        this.reload()
                    } else {
                        console.error("API 请求失败", res);
                    }
                }).catch(error => {
                    console.error("API 请求错误", error);
                });
            }
        },
        //判断是否自己的帖子
        isuserpost(){
            if(this.stuId==this.user.studentId){
                this.isedit=true;
            }
        },
        //跳转作者个人中心
        touser(){
            console.log("点击");
            this.$router.push({ path: '/personal', query: { userid: this.post.author} })
        }
    },


    //生命周期
    created() {
        this.user = JSON.parse(sessionStorage.getItem("user"));
        console.log("用户信息:", this.user);  // 查看 user 的实际内容
        console.log(this.user.studentId)
        this.postId = this.$route.query.id,
        this.type = this.$route.query.type;
        this.stuId = this.$route.query.stuId;
        this.getPost();
        this.getComment();
        this.getUserIsLike();
        this.isuserpost();
    },
    //计算属性
    computed: {
        displayContent() {
            return this.type == 1 ? '生活分享' : '学习交流';
        },
        isnumberLikes() {
            return this.numberLikes == null ? 0 : this.numberLikes
        }
    }


}
</script>

<style scoped>
.detail {}

.content {
    width: 1026px;
    margin: 20px auto;

}

.top {
    display: flex;
}

.text {
    font-size: 14px;
}

.item {
    padding: 18px 0;
}

.box-card {}

.publishinformation {}

.publishinformation>span {
    margin-top: 12px;
    color: #909399;
    font-family: 'PingFang SC';
}

.comment {
    height: 60px;
    line-height: 60px;
    display: flex;
    align-items: center;
    margin-top: 36px;
}

.commentlist {
    margin-top: 46px;
}

.comment_user {
    display: flex;
    align-items: center;
    margin-top: 20px;
    padding: 20px 26px;
}

.Footer {
    position: relative;
}

/* elementui 样式 */
.el-card {
    margin-bottom: 20px;
    /* 保证组件间的间距 */
}
</style>